package com.cs.controller;


import com.alipay.easysdk.factory.Factory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cs.config.AlipayConfig;
import com.cs.constants.Constants;
import com.cs.entity.MaintainOrder;
import com.cs.entity.Model;
import com.cs.entity.PayOrder;
import com.cs.service.MaintainOrderService;
import com.cs.service.ModelService;
import com.cs.service.PayOrderService;
import com.cs.utils.AlipayUtil;
import com.cs.utils.MathUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 订单支付信息 前端控制器
 * </p>
 *
 * @author cs
 * @since 2021-08-05
 */

@Slf4j
@RestController
@RequestMapping("/api/pay")
public class PayOrderController {

    @Autowired
    private AlipayUtil alipayUtil;

    @Autowired
    private MaintainOrderService maintainOrderService;

    @Autowired
    private ModelService modelService;

    @Autowired
    private AlipayConfig alipayConfig;

    @Autowired
    private PayOrderService payOrderService;

    @RequestMapping("aliPay")
    public String aliPay(String orderNo){
        log.info("oderNo------------->>> {}",orderNo);
        String result = "";
        //1.modelName
        //通过订单号，获取订单对象
        QueryWrapper<MaintainOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("orderNo",orderNo);
        MaintainOrder maintainOrder = maintainOrderService.getOne(wrapper);
        //通过订单对象，获取商品id，通过商品id获取商品对象，对象中有商品名称
        Long modelId = maintainOrder.getModelId();
        Model model = modelService.getById(modelId);
        //2.payNo
        StringBuffer buffer = new StringBuffer(orderNo);
        String payNo = buffer.toString();
        buffer.append(MathUtils.random());//添加随机数
        //3.价格
        BigDecimal subscription = maintainOrder.getSubscription();
        result = alipayUtil.aliPagePay(model.getModelName(),payNo,subscription.toString());
        //保存支付订单表
        //先保存，但是没有支付宝的订单号
        PayOrder payOrder = new PayOrder(orderNo,payNo,maintainOrder.getUserId(),subscription,1,Constants.Order.PayType.DEPOSIT,Constants.Order.PayStaus.UN_PAY);
        payOrder.setCreatedUserId(maintainOrder.getUserId());
        payOrderService.save(payOrder);
        return result;
    }

    //同步的方法，再支付页面倒计时之后支付宝会访问我们
    @GetMapping("aliPay/returnUrl")
    public String returnUrl(HttpServletRequest request){
        String result = "";
        //1.验签 - 有消息告诉我支付成功了，但是还应该获取这些消息，铜鼓哦支付宝给我们的接口去验证一边

        //支付宝表单内容
        Map<String, String[]> parameterMap = request.getParameterMap();
        //遍历这个map，获取值放到自己的map中
        Map<String, String> map = new HashMap<>();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            String mapkey = entry.getKey();
            //支付宝给我们的value是一个String数组，但是只有第一个元素有值
            String mapvalue = entry.getValue()[0];
            map.put(mapkey,mapvalue);
        }
        //调用接口，得到返回值
        boolean flag = false;
        try {
            //验签可能会失败. 1:可能在维护 2.中文乱码
            flag = Factory.Payment.Common().verifyNotify(map);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //验签成功之后，应该修改支付订单表
        QueryWrapper<PayOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("orderNo",map.get("out_trade_no"));
        PayOrder one = payOrderService.getOne(wrapper);
        one.setAliTradeNo(map.get("trade_mo")); //设置阿里的订单号
        one.setStatus(Constants.Order.PayStaus.SUCCESS); //设置支付状态为成功
        payOrderService.updateById(one);//修改

        //2.电商网站下单成功影噶i修改库存，修改订单状态，因为是维修网站，所以只炫耀修改订单的状态，变成已付定付
        QueryWrapper<MaintainOrder> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("orderNo",map.get("out_trade_no"));
        MaintainOrder maintainOrder = maintainOrderService.getOne(wrapper2);
        maintainOrder.setStatus(Constants.Order.MaintainStatus.PAY_DEPOSIT);//修改定金状态为支付定金
        maintainOrderService.updateById(maintainOrder);

        //3.跳转回电商网站
        //result = alipayConfig.getSuccessUrl();
        return "redirect: http://localhost:8081/";
    }
}

